/**
 * created by 小卷毛, 2021/4/28
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.example.myapplication.util

import android.content.Context
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.io.PrintWriter
import java.io.StringWriter
import java.text.SimpleDateFormat
import java.util.*


/**
 * 描 述：应用崩溃日志收集工具
 * 作 者：小卷毛  2021-04-28 16:35
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class CrashHandler constructor(
    private val context: Context
) : Thread.UncaughtExceptionHandler {

    override fun uncaughtException(t: Thread, e: Throwable) {
        saveThrowableMessage(getStackTraceInfo(e))
    }

    /**
     * 获取错误的信息
     */
    private fun getStackTraceInfo(throwable: Throwable) =
        StringWriter().let {
            PrintWriter(it).apply {
                throwable.printStackTrace(this)
            }.close()

            it.toString()
        }

    /**
     * 保存到本地 /storage/emulated/0/Android/data/包名/files/crashLog
     */
    private fun saveThrowableMessage(errorMessage: String) {
        if (errorMessage.isEmpty()) return

        val cacheDir = if (isSDcardExsit()) context.getExternalFilesDir(null) else context.filesDir

        val fileDir = File(cacheDir, "crashLog")
        if (!fileDir.exists()) fileDir.mkdirs()

        FileOutputStream(
            File(fileDir, "${SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())}.txt"),
            true
        ).apply {
            write("$errorMessage\n".toByteArray())
            close()
        }
    }

    /**
     * 判断外部存储是否存在
     */
    private fun isSDcardExsit() = Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()

}